package com.its.controller;

import com.its.domain.BaseResult;
import com.its.domain.CodeEnum;
import com.its.manager.pojo.Admin;
import com.its.pojo.AdminLoginResultDTO;
import com.its.service.AdminService;
import com.its.utils.AdminJwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;

@RestController
@RequestMapping("/Admin")
public class AdminController {

    //新增业务层属性
    @Autowired
    private AdminService adminService;

    @Autowired
    private PasswordEncoder passwordEncoder;//注入密码加密工具

    @Autowired
    private AdminJwtUtils jwtUtils;

    @PostMapping("/test")
    public String test() {
        return "后台服务已连通";
    }

    // 管理员登录接口
    @PostMapping("/AdminLogin")
    public BaseResult<Admin> adminLogin(@RequestBody Admin admin) {
        // 1. 根据用户名查找数据库中的管理员信息
        Admin adminRes = adminService.getByUsername(admin.getUsername());

        // 2. 判断用户是否存在
        if (adminRes == null) {
            return BaseResult.error(CodeEnum.LOGIN_NAME_PASSWORD_ERROR);
        }

        // 3. 使用 Spring Security 的 passwordEncoder 校验密码
        boolean match = passwordEncoder.matches(admin.getPassword(), adminRes.getPassword());
        if (!match) {
            return BaseResult.error(CodeEnum.LOGIN_NAME_PASSWORD_ERROR);
        }

        // 4. 登录成功，为了安全，清空密码字段
        adminRes.setPassword(null);

        // 登录成功，生成 token
        String token = jwtUtils.createToken(admin.getUsername());

        // 登录成功后，构造一个认证对象（不依赖默认UserDetailsService）
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(adminRes.getUsername(), null, Collections.emptyList());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        AdminLoginResultDTO adminLoginResultDTO = new AdminLoginResultDTO();
        adminLoginResultDTO.setAdmin(adminRes);
        adminLoginResultDTO.setToken(token);

        return BaseResult.ok(adminRes);
    }
}
